from motor.motor_asyncio import AsyncIOMotorClient
from core.config import config

class DBClient:
    def __init__(self):
        self.client = None
        self.db = None

    async def connect(self):
        self.client = AsyncIOMotorClient(f"mongodb://{config.database.username}:{config.database.password}@{config.database.host}:{config.database.port}")
        self.db = self.client[config.database.database]
        print("Connected to MongoDB!")

    async def disconnect(self):
        if self.client:
            self.client.close()
            print("Disconnected from MongoDB!")

db_client = DBClient()

async def get_db():
    # print("获取数据库连接:", db_client.db is not None)  # 调试日志
    try:
        yield db_client.db
    finally:
        pass  # 连接由 db_client 管理，不需要在这里关闭    